#!/usr/bin/python

import ConfigParser
import threading
import logging
import sys
import os
import shlex
import subprocess
import time

cmdServer21 = None
cmdServer22 = None
cmdServer23 = None
cmdServer24 = None
cmdServer25 = None
serverSysDir = None



		
def start(cmdServer):
	logging.info('Server online')
	target = subprocess.Popen(cmdServer, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	target.communicate()
	return
		
def startLoop(cmdServer):
	while True:
		logging.info('starting server...')
		start(cmdServer)
		logging.info('Server Crashed... Restarting server!')
	return True
		
def startThread(cmdServer, num):
	title = "ServerThread-" + str(num)
	serverThread = threading.Thread(name=title, target=startLoop, args=(cmdServer,))
	serverThread.setDaemon(True)
	serverThread.start()
	return True

def getConfig():
	global cmdServer21, cmdServer22, cmdServer23, cmdServer24, cmdServer25, serverSysDir
	config = ConfigParser.RawConfigParser()
	config.read('config.conf')

	cmdServer21 = shlex.split(config.get('Settings','server21'))
	cmdServer22 = shlex.split(config.get('Settings','server22'))
	cmdServer23 = shlex.split(config.get('Settings','server23'))
	cmdServer24 = shlex.split(config.get('Settings','server24'))
	cmdServer25 = shlex.split(config.get('Settings','server25'))
	serverSysDir = config.get('Settings','server-system-dir')
	return True

if __name__ == '__main__':
	logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(asctime)s - %(threadName)-10s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
	getConfig()
	os.chdir(serverSysDir)
	
	
	startThread(cmdServer21, 21)
	time.sleep(5)
	startThread(cmdServer22, 22)
	time.sleep(5)
	startThread(cmdServer23, 23)
	time.sleep(5)
	startThread(cmdServer24, 24)
	time.sleep(5)
	startThread(cmdServer25, 25)
	
	while True:
		time.sleep(1)

